package com.sx.wechat.controller.teacher;

import com.alibaba.druid.sql.PagerUtils;
import com.alibaba.druid.util.JdbcConstants;
import com.alibaba.fastjson.JSONObject;
import com.sx.core.model.Information;
import com.sx.core.model.Order;
import com.sx.core.mybatis.SessionTemplate;
import com.sx.core.page.Page;
import com.sx.core.vo.JsonReaderResponse;
import com.sx.core.vo.Params;
import com.sx.wechat.controller.BaseController;
import com.sx.wechat.security.AuthenticationHolder;
import com.sx.wechat.service.OrderService;
import com.sx.wechat.shiro.InformationPrincipal;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * Created by lihao on 2017/6/29.
 */
@RequestMapping("tc/order")
@RestController
public class OrderController extends BaseController {
    @Autowired
    SessionTemplate sessionTemplate;

    @Autowired
    OrderService orderService;

    @RequestMapping("list_lab")
    public JsonReaderResponse list_lab() {
        String sql="select * from t_laboratory";
        return new JsonReaderResponse(jdbcTemplate.queryForList(sql));

    }
    @RequestMapping("list_lesson")
    public JsonReaderResponse list_lesson() {
        String sql="select * from t_lesson";
        return new JsonReaderResponse(jdbcTemplate.queryForList(sql));
    }
    @RequestMapping("list_class")
    public JsonReaderResponse list_student() {
        String sql="select * from t_class";
        return new JsonReaderResponse(jdbcTemplate.queryForList(sql));
    }
    @RequestMapping("list_student/{classid}")
    public JsonReaderResponse list_class(@PathVariable String classid) {
        Page<Information> listPage=sessionTemplate.listPage(Information.class,"select_list",1,10000,new Params().p("type","1").p("classid",classid));
        return new JsonReaderResponse(listPage.getContent(),listPage.getTotalElements());
    }


    @RequestMapping("list_content")
    public JsonReaderResponse list_content() {
        String sql="select * from t_sx_content";
        return new JsonReaderResponse(jdbcTemplate.queryForList(sql));

    }


     @RequestMapping("list_lab_order")
    public JsonReaderResponse list_lab_order(@RequestBody Map<String,Object> params) {
        String r_sql="select * from t_region order by idx asc";
        InformationPrincipal information= AuthenticationHolder.getCurrentInfo();
        List<Map<String,Object>> list=jdbcTemplate.queryForList(r_sql);
        params.put("types",new String[]{"1","2"});
        for(Map<String,Object> map:list){
            params.put("regionid",map.get("id"));
            map.put("items",sessionTemplate.list(Order.class,"list_order",params));
        }
        return new JsonReaderResponse(list).addExtra(sessionTemplate.get(Information.class,information.getId()));

    }

    @RequestMapping("list_order")
    public JsonReaderResponse list_order(@RequestBody Map<String,Object> params) {
        InformationPrincipal information= AuthenticationHolder.getCurrentInfo();
        int page= NumberUtils.toInt(ObjectUtils.toString(params.get("page")),1);
        int limit= NumberUtils.toInt(ObjectUtils.toString(params.get("limit")),25);
        params.put("teacherid",information.getId());
        Page<Order> listPage=sessionTemplate.listPage(Order.class,"list_order",page,limit,params);
        return new JsonReaderResponse(listPage.getContent(),listPage.getTotalElements());
    }
    @RequestMapping("get_order")
    public JsonReaderResponse get_order(String id) {
        String r_sql="SELECT " +
                "o.*," +
                "l.name as lessionname," +
                "b.name as labname " +
                "FROM t_order o " +
                "LEFT JOIN t_lesson l on o.lessonid=l.id " +
                "left JOIN t_laboratory b on o.labid=b.id " +
                "WHERE o.id=? ";
        return new JsonReaderResponse().addExtra(jdbcTemplate.queryForMap(r_sql,id));
    }


    @RequestMapping("last_order_his")
    public JsonReaderResponse last_order_his() {
        InformationPrincipal information= AuthenticationHolder.getCurrentInfo();
        List<Map<String,Object>> last_order=jdbcTemplate.queryForList("SELECT " +
                "o.*," +
                "l.name as lessionname," +
                "b.name as labname " +
                "FROM t_order o " +
                "LEFT JOIN t_lesson l on o.lessonid=l.id " +
                "left JOIN t_laboratory b on o.labid=b.id " +
                "WHERE o.teacherid=? " +
                "ORDER BY o.time DESC limit 1",information.getId());
        if(last_order.isEmpty()){
            return new JsonReaderResponse();
        }
        return new JsonReaderResponse().addExtra(last_order.get(0));
    }
    @RequestMapping("last_order_his_user")
    public JsonReaderResponse last_order_his_user(@RequestBody JSONObject params) {
        InformationPrincipal information= AuthenticationHolder.getCurrentInfo();
        params.put("teacherid",information.getId());
        int page= NumberUtils.toInt(ObjectUtils.toString(params.get("page")));
        int limit= NumberUtils.toInt(ObjectUtils.toString(params.get("limit")));
        String sql="select rs.*,\n" +
                "i.id,s.score,i.name,i.sno,i.sex,i.idno," +
                "o.startdate,o.teachername,o.lessonname,o.labname,o.yutime,o.week,o.regionname," +
                "c.title\n" +
                "from t_order_rec_stu rs\n" +
                "JOIN t_order o ON rs.orderid=o.id \n" +
                "join t_information i on rs.stuid=i.id\n" +
                "join t_sx_content c on c.id=o.contentid\n" +
                "LEFT JOIN t_all_score s on rs.id=s.rsid\n" +
                "where rs.status=1 AND  o.teacherid=:teacherid \n";
        String keyword=params.getString("keyword");
        if(StringUtils.isNotBlank(keyword)){
            sql+=" AND (i.name LIKE  CONCAT('%',:keyword,'%') OR i.sno LIKE  CONCAT('%',:keyword,'%'))";
        }
        String orderid=params.getString("orderid");
        if(StringUtils.isNotBlank(orderid)){
            sql+=" AND rs.orderid=:orderid ";
        }
//        String count_sql= PagerUtils.count(sql, JdbcConstants.MYSQL);
//        long count=namedParameterJdbcTemplate.queryForObject(count_sql,params,Long.class);



        sql+=" ORDER BY s.score DESC";

        List<Map<String,Object>> list=namedParameterJdbcTemplate.queryForList(sql,params);


        return new JsonReaderResponse(list);
    }

    @RequestMapping("list_order_his")
    public JsonReaderResponse list_order_his(@RequestBody JSONObject params) {
        InformationPrincipal information= AuthenticationHolder.getCurrentInfo();
        params.put("teacherid",information.getId());
        int page= NumberUtils.toInt(ObjectUtils.toString(params.get("page")));
        int limit= NumberUtils.toInt(ObjectUtils.toString(params.get("limit")));
        String sql="select rs.*,\n" +
                "i.id,s.score,i.name,i.sno,i.sex,i.idno," +
                "o.startdate,o.teachername,o.lessonname,o.labname,o.yutime,o.week,o.regionname," +
                "c.title\n" +
                "from t_order_rec_stu rs\n" +
                "JOIN t_order o ON rs.orderid=o.id \n" +
                "join t_information i on rs.stuid=i.id\n" +
                "join t_sx_content c on c.id=o.contentid\n" +
                "LEFT JOIN t_all_score s on rs.id=s.rsid\n" +
                "where rs.status=1 AND  o.teacherid=:teacherid \n";
        String keyword=params.getString("keyword");
        if(StringUtils.isNotBlank(keyword)){
            sql+=" AND (i.name LIKE  CONCAT('%',:keyword,'%') OR i.sno LIKE  CONCAT('%',:keyword,'%'))";
        }
        String orderid=params.getString("orderid");
        if(StringUtils.isNotBlank(orderid)){
            sql+=" AND rs.orderid=:orderid ";
        }
//        String count_sql= PagerUtils.count(sql, JdbcConstants.MYSQL);
//        long count=namedParameterJdbcTemplate.queryForObject(count_sql,params,Long.class);



        sql+=" ORDER BY s.score DESC";

        List<Map<String,Object>> list=namedParameterJdbcTemplate.queryForList(sql,params);


        return new JsonReaderResponse(list);
    }

    @RequestMapping("list_stu_order")
    public JsonReaderResponse list_stu_order(@RequestBody JSONObject params) {
        int page= NumberUtils.toInt(ObjectUtils.toString(params.get("page")));
        int limit= NumberUtils.toInt(ObjectUtils.toString(params.get("limit")));
        String stuid= params.getString("stuid");
        String sql="select " +
                "o.*," +
                "rs.status,rs.lastupdatedate," +
                "sc.title," +
                "s.score " +
                "from t_order_rec_stu rs " +
                "JOIN t_order o on o.id=rs.orderid " +
                "JOIN t_sx_content sc on sc.id=o.contentid " +
                "LEFT JOIN t_all_score s on s.rsid=rs.id " +
                "WHERE rs.stuid=:stuid " +
                "AND rs.status=1 " +
                "ORDER BY o.startdate ASC ";

        String count_sql= PagerUtils.count(sql, JdbcConstants.MYSQL);
        long count=namedParameterJdbcTemplate.queryForObject(count_sql,params,Long.class);

        sql=PagerUtils.limit(sql,JdbcConstants.MYSQL,(page-1)*limit,limit);

        List<Map<String,Object>> list=namedParameterJdbcTemplate.queryForList(sql,params);


        return new JsonReaderResponse(list,count,page,limit);
    }




    @RequestMapping("sub_order")
    @Transactional
    public JsonReaderResponse sub_order(@RequestBody JSONObject params) {
        InformationPrincipal principal= AuthenticationHolder.getCurrentInfo();
        return orderService.sub_order(params,principal.getId());
    }
    @RequestMapping("cancel_order")
    @Transactional
    public JsonReaderResponse cancel_order(String id) {
        sessionTemplate.delete(Order.class,id);
        jdbcTemplate.update("DELETE FROM t_order_rec_stu WHERE orderid=?",id);
        return new JsonReaderResponse();
    }










}
